package main

import (
	"fmt"
	"time"
)

//能发送数据给 channel，不能接收数据
func sc(ch chan<- string) {
	ch <- "hello world"
}

func f1(ch chan string) {
	time.Sleep(2 * time.Second)
	ch <- "first arrive"
}

func f2(ch chan string) {
	time.Sleep(time.Second)
	ch <- "sencond arrive"
}

func main() {
	c := make(chan string)
	go func() { c <- "hello" }()

	//接收方channel会一直等待发送方发数据到channel
	msg := <-c
	fmt.Println("msg is:", msg)

	//单向channel
	ch := make(chan string)
	go sc(ch)
	fmt.Println(<-ch)

	//使用select语句在Go routine中处理多个channel
	c1 := make(chan string)
	c2 := make(chan string)
	go f1(c1)
	go f2(c2)
	select {
	case s1 := <-c1:
		fmt.Println(s1)
	case s2 := <-c2:
		fmt.Println(s2) //out sencond arrive
	}

	//使用缓冲区channel，如果缓冲区已满，发送到该channel的消息将被阻塞
	ch1 := make(chan string, 2)
	ch1 <- "hello"
	ch1 <- "world"
	//ch1 <- "!!!"
	fmt.Println(<-ch1)
	fmt.Println(<-ch1)
}
